<?php
/**
 * Created by PhpStorm.
 * User: 14775
 * Date: 2017/8/31
 * Time: 9:41
 */

namespace Home\Controller;


use Common\Controller\HomebaseController;
use Common\Lib\RedisHandle;
use Common\Lib\SMSLib;
use Common\Model\MembersModel;
use Common\ModelSQ\ERPUser;

class PublicController extends HomebaseController
{

    public function _initialize()
    {
        parent::_initialize();
    }


    //会员登录页
    public function Login()
    {
        $url = I('url');
        if (!$url) {
            $url = U('member/index');
        }
        $this->assign('url', $url);
        $this->display();
    }

    //会员登录页
    public function quickLogin()
    {
        $url = I('url');
        if (!$url) {
            $url = U('member/index');
        }
        $this->assign('url', $url);
        $this->display();
    }


    //会员登录
    public function doLogin()
    {
        $mobile = I("post.mobile");
        $password = I("post.password");
        $quick = I("post.quick",0);

        if($quick){
            $server_vcode = RedisHandle::getSMSVCode($mobile);
            if($server_vcode != $password){
                $this->ajaxReturn(array('code' => 400, 'message' => '验证码不正确'));
            }
        }

        /*快速登录，本地数据库没有查询erp系统有则同步数据，无则提示注册-----huangld20180109 start*/
        //查询会员信息
        $erpUser = new ERPUser();
        $member = M('members')->where(array('telephone' => $mobile))->find();
        if($quick && !$member){

//        查询会员信息
            $data = array(
                'telephone' => "$mobile"
            );
            $erp_userinfo = $erpUser->getMember($data);
            error_log(print_r($erp_userinfo, 1));
            if ($erp_userinfo['success'] && $erp_userinfo['code'] == 1000) {
                //erp系統已存在会员
                $member['member_code'] = $erp_userinfo['data']['member_code'];
                $member['account_no'] = $erp_userinfo['data']['account_no'];
                $member['member_name_chn'] = $erp_userinfo['data']['member_name_chn'];
                $member['sex'] = $erp_userinfo['data']['sex'];
                $member['address'] = $erp_userinfo['data']['address'];
                $member['postal_code'] = $erp_userinfo['data']['postal_code'];
                $member['email'] = $erp_userinfo['data']['email'];
                $member['certificate_type'] = $erp_userinfo['data']['certificate_type'];
                $member['id_no'] = $erp_userinfo['data']['id_no'];
                $member['dob'] = $erp_userinfo['data']['dob'];
                $member['telephone_country_code'] = $erp_userinfo['data']['telephone_country_code'];
                $member['marital_status'] = $erp_userinfo['data']['marital_status'];
                $member['integral'] = isset($erp_userinfo['data']['bonus_point']) ? $erp_userinfo['data']['bonus_point'] : 0;
                //注册到本地数据库
                $memberModel = new MembersModel();

                $memberModel->register($member);
            } else if (!$erp_userinfo['success'] && $erp_userinfo['code'] == 1004) {
                $this->ajaxReturn(array('code' => 404, 'message' => '该手机号未注册'));

            }else{
                $this->ajaxReturn(array('code' => 404, 'message' => '系统未知错误'));
            }
        }else if( !$quick && !$member) { /*非快捷登录则查询本地数据库。无数据则提示注册*/
            $this->ajaxReturn(array('code' => 404, 'message' => '该手机号未注册'));
        }
        /*快速登录，本地数据库没有查询erp系统有则同步数据，无则提示注册-----huangld20180109 end*/

        if(!$quick){
            if ($member['password'] != md5($password)) {
                $this->ajaxReturn(array('code' => 400, 'message' => '用户名或密码不正确'));
            }
        }

        $this->setMember($member['telephone'], $member);
        $this->ajaxReturn(array('code' => 200, 'message' => '登录成功'));

    }

    //短信验证码
    public function sendSms()
    {
        $mobile = I('post.mobile');

        $member = M('members')->where(array('telephone' => $mobile))->find();
        if (!$member) {
            $this->ajaxReturn(array('code' => 404, 'message' => '该手机号未注册'));
        }

        $sms = new SMSLib();
        $vcode = rand(10000,99999);
        RedisHandle::saveSMSVCode($mobile, $vcode);
        $result = $sms->sendSMS($mobile,'【夏都小镇】您的短信验证码是:'.$vcode.'，请注册页面中输入并完成验证（30分钟有效），如非本人操作，请忽略此短信。本条短信免费。');
        $this->ajaxReturn(array('code' => 200, 'message' => '发送成功'));
    }


    public function doLogout()
    {
        $member = $this->getMember();
        $this->setMember($member['telephone'], null);
        $this->setWxUser($member['wx_openid'], null);

        $this->redirect('public/login');

    }


    //会员注册
    public function Register()
    {
        if ($this->getWxUser()) {
            $this->display();
        } else {
            $this->redirect('Wx/Wxauth/index', array('action' => 'register'));
        }
    }

    public function sendvcode()
    {

        $mobile = I('post.mobile');
        $sms = new SMSLib();
        $vcode = rand(10000,99999);
        RedisHandle::saveSMSVCode($mobile,$vcode);
        $result = $sms->sendSMS($mobile,'【夏都小镇】您的短信验证码是:'.$vcode.'，请注册页面中输入并完成验证（30分钟有效），如非本人操作，请忽略此短信。本条短信免费。');

        $this->ajaxReturn(array('code' => 200, 'message' => '发送成功'));
    }

    public function doRegister()
    {

        $api_config = C('ERPUSER');

        $mobile = I('post.mobile');
        $vcode = I('post.vcode');
        $password = I('post.password');

        $wx_user = $this->getWxUser();


        if (!$wx_user) {
            $this->ajaxReturn(array('code' => 400, 'message' => '请刷新页面后重试'));
        }


        //1.校验验证码

        if(!$vcode){
            $this->ajaxReturn(array('code' => 400, 'message' => '请输入验证码'));
        }

        $server_vcode =RedisHandle::getSMSVCode($mobile);
        if($server_vcode != $vcode){
            $this->ajaxReturn(array('code' => 400, 'message' => '验证码不正确'));
        }


        //2.校验手机号
        $memberModel = new MembersModel();
        if ($memberModel->where(array('telephone' => $mobile))->find()) {
            $this->ajaxReturn(array('code' => 401, 'message' => '该手机号码已被注册'));
        }


        $member = array(
            'telephone' => $mobile,
            'password' => md5($password),
            'wx_openid' => $wx_user['openid'],
            'head_img' => $wx_user['headimgurl'],
            'nickname' => $wx_user['nickname'],
            'register_date' => date('Y-m-d H:i:s')
        );


        //同步会员信息

        $erpUser = new ERPUser();

//        查询会员信息
        $data = array(
            'telephone' => "$mobile"
        );
        $erp_userinfo = $erpUser->getMember($data);
        if ($erp_userinfo['success'] && $erp_userinfo['code'] == 1000) {
            //已存在会员
            $member['member_code'] = $erp_userinfo['data']['member_code'];
            $member['account_no'] = $erp_userinfo['data']['account_no'];
            $member['member_name_chn'] = $erp_userinfo['data']['member_name_chn'];
            $member['sex'] = $erp_userinfo['data']['sex'];
            $member['address'] = $erp_userinfo['data']['address'];
            $member['postal_code'] = $erp_userinfo['data']['postal_code'];
            $member['email'] = $erp_userinfo['data']['email'];
            $member['certificate_type'] = $erp_userinfo['data']['certificate_type'];
            $member['id_no'] = $erp_userinfo['data']['id_no'];
            $member['dob'] = $erp_userinfo['data']['dob'];
            $member['telephone_country_code'] = $erp_userinfo['data']['telephone_country_code'];
            $member['marital_status'] = $erp_userinfo['data']['marital_status'];
            $member['integral'] = isset($erp_userinfo['data']['bonus_point']) ? $erp_userinfo['data']['bonus_point'] : 0;

        } else if (!$erp_userinfo['success'] && $erp_userinfo['code'] == 1004) {
            //不存在
            $data = array(
                'issue_store' => $api_config['ISSUE_STORE'],
                'telephone' => $mobile,
                'member_name_chn' => '',
                'sex' => '',
                'address' => '',
                'postal_code' => '',
                'email' => '',
                'certificate_type' => null,
                'id_no' => null,
                'issue_by' => '微信'
            );

            $erp_userinfo = $erpUser->createMember($data);
            $member['member_code'] = $erp_userinfo['data']['member_code'];
        } else {
            $data = array('code' => 400, 'message' => '系统异常,请重试');
            $this->ajaxReturn($data);
        }


        if (!$member['member_code']) {
            $data = array('code' => 400, 'message' => '系统异常,请重试');
            $this->ajaxReturn($data);
        }

        $memberModel->register($member);

        $member = $memberModel->getMemberByMobile($member['telephone']);

        $this->setMember($member['telephone'], $member);

        $data = array('code' => 200, 'message' => '注册成功');
        $this->ajaxReturn($data);
    }
}